package cn.mrlong.idcardphoto.camera;

import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;
import java.util.List;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private SensorControler sensorControler;
    private Camera camera;

    public CameraPreview(Context context) {
        super(context);
        init(context);
    }

    public CameraPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CameraPreview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    private void init(Context context) {
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);
        holder.setKeepScreenOn(true);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        //获得传感器控制
        sensorControler = SensorControler.getInstance(context);
        //相机焦点控制监听
        sensorControler.setCameraFocusListener(new SensorControler.CameraFocusListener() {
            @Override
            public void onFocus() {
                autoFocus();
            }
        });
    }

    /**
     * 闪光灯 开关
     *
     * @return 是否开启
     */
    public boolean switchFlashLight() {
        if (null != camera) {
            Camera.Parameters parameters = camera.getParameters();
            //如果闪光灯是关 则打开
            if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF)) {
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(parameters);
                return true;
            } else {
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camera.setParameters(parameters);
                return false;
            }
        }
        return false;
    }

    /**
     * 拍摄照片
     *
     * @param callback
     */
    public void takePic(Camera.PictureCallback callback) {
        if (null != camera) {
            camera.takePicture(null, null, callback);
        }
    }

    /**
     * 自动对焦
     */
    public void autoFocus() {
        if (null != camera) {
            camera.autoFocus(null);
        }
    }

    /**
     * SurfaceHolder创建
     *
     * @param holder
     *
     */
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        camera = CameraUtils.openCamera();
        if (camera != null) {
            try {
                camera.setPreviewDisplay(holder);

                Camera.Parameters parameters = camera.getParameters();
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    //竖屏拍照时，需要设置旋转90度，否者看到的相机预览方向和界面方向不相同
                    camera.setDisplayOrientation(90);
                    parameters.setRotation(90);
                } else {
                    camera.setDisplayOrientation(0);
                    parameters.setRotation(0);
                }
                Camera.Size bestSize = getBestSize(parameters.getSupportedPreviewSizes());
                if (bestSize != null) {
                    parameters.setPreviewSize(bestSize.width, bestSize.height);
                    parameters.setPictureSize(bestSize.width, bestSize.height);
                } else {
                    parameters.setPreviewSize(1920, 1080);
                    parameters.setPictureSize(1920, 1080);
                }
                camera.setParameters(parameters);
                camera.startPreview();
                autoFocus();//首次对焦
                //定时对焦
                //mAutoFocusManager = new AutoFocusManager(camera);
            } catch (Exception e) {
                //Log.d(TAG, "Error setting camera preview: " + e.getMessage());
                try {
                    Camera.Parameters parameters = camera.getParameters();
                    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                        //竖屏拍照时，需要设置旋转90度，否者看到的相机预览方向和界面方向不相同
                        camera.setDisplayOrientation(90);
                        parameters.setRotation(90);
                    } else {
                        camera.setDisplayOrientation(0);
                        parameters.setRotation(0);
                    }
                    camera.setParameters(parameters);
                    camera.startPreview();
                    autoFocus();//首次对焦
                    //定时对焦
                    //mAutoFocusManager = new AutoFocusManager(camera);
                } catch (Exception e1) {
                    e.printStackTrace();
                    camera = null;
                }
            }
        }
//        camera = CameraUtils.openCamera();
//        if (null != camera) {
//            try {
//                setCameraParms(surfaceHolder);
//            } catch (IOException e) {
//                e.printStackTrace();
//                try {
//                    setCameraParms(surfaceHolder);
//                } catch (IOException e1) {
//                    e1.printStackTrace();
//                    camera = null;
//                }
//            }
//        }
    }

    /**
     * 设置相机的参数
     *
     * @param surfaceHolder
     * @throws IOException
     */
    private void setCameraParms(SurfaceHolder surfaceHolder) throws IOException {
        camera.setPreviewDisplay(surfaceHolder);
        //设置参数
        Camera.Parameters parameters = camera.getParameters();
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            camera.setDisplayOrientation(90);//竖屏旋转 90度
            parameters.setRotation(90);
        } else {
            camera.setDisplayOrientation(0);//竖屏旋转 90度
            parameters.setRotation(0);
        }
        Camera.Size bastSize = getBestSize(parameters.getSupportedPreviewSizes());
        if (null != bastSize) {
            parameters.setPictureSize(bastSize.width, bastSize.height);
            parameters.setPreviewSize(bastSize.width, bastSize.height);
        } else {
            parameters.setPreviewSize(1920, 1080);
            parameters.setPictureSize(1920, 1080);
        }
        camera.setParameters(parameters);
        camera.startPreview();
        autoFocus();
    }


    /**
     * Android相机的预览尺寸都是4:3或者16:9，这里遍历所有支持的预览尺寸，得到16:9的最大尺寸，保证成像清晰度
     *
     * @param sizes
     * @return 最佳尺寸
     */
    private Camera.Size getBestSize(List<Camera.Size> sizes) {
        Camera.Size bestSize = null;
        for (Camera.Size size : sizes) {
            if ((float) size.width / (float) size.height == 16.0f / 9.0f) {
                if (bestSize == null) {
                    bestSize = size;
                } else {
                    if (size.width > bestSize.width) {
                        bestSize = size;
                    }
                }
            }
        }
        return bestSize;
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    public void onStop() {
        if (null != sensorControler) {
            sensorControler.onStop();
        }
        release();
    }

    /**
     * 释放资源
     *
     * @param surfaceHolder
     */
    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        release();
    }

    private void release() {
        if (null != camera) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    public void startPreview() {
        if (camera != null) {
            camera.startPreview();
        }
    }
}

